<?php
namespace app\common\model;

use think\Model;

class APP extends Model{
     ##定义当前模型表单
    public $form;
    
    
    protected static function init(){
        ##新增前回调 这里的$model就是$this
        self::beforeInsert(function($model){
            if(method_exists($model,'before_insert')) return $model->before_insert($model->data);
        });
        ##新增后回调
        self::afterInsert(function($model){
            if(method_exists($model,'after_insert')) return $model->after_insert($model->data);
        });
        ##修改前回调
        self::beforeUpdate(function($model){
            if(method_exists($model,'before_update')) return $model->before_update($model->data);
        });
        ##修改后回调
        self::afterUpdate(function($model){
            if(method_exists($model,'after_update')) return $model->after_update($model->data);
        });
        ##写入前回调（insert和update都会先调这个方法）
        self::beforeWrite(function($model){            
            if(method_exists($model,'before_write')) return $model->before_write($model->data);
        });
        ##写入后回调
        self::afterWrite(function($model){
            if(method_exists($model,'after_write')) return $model->after_write($model->data);
        });
        ##删除前回调
        self::beforeDelete(function($model){
            if(method_exists($model,'before_delete')) return $model->before_delete($model->data);
        });
        ##删除后回调
        self::afterDelete(function($model){
            if(method_exists($model,'after_delete')) return $model->after_delete($model->data);
        });
    }    


    public function before_insert(){
        
    }
    public function after_insert(){
        
    }
    public function before_update(){
        
    }
    public function after_update(){
        
    }
    public function before_write(){
        
    }
    public function after_write(){
        
    }
    public function before_delete(){
        
    }
    public function after_delete(){
        
    }
    ##多表关联查询（$main_table：需要关联的表（必需）；$extro_table：被关联的表（必需）；$main_table_field_name：查询到的数据中附表信息字段名）
    public function has_maney($main_table,$extro_table,$c_field=1,$c_value=1,$select_field=true){
        $model=model($main_table);
        $lists=collection($model->select())->toArray();
        foreach($lists as $k=>$v){
            $v[$extro_table]=$model->get($v['id'])->hasMany($extro_table)->where($c_field,$c_value)->field($select_field)->select();
            foreach($v[$extro_table] as $k1=>$v1){
                $v[$extro_table][$k1]=$v1->toArray();
            }
            $x[]=$v;
        }
        
        return $x;
        
    }
}